<template>
  <div class="phone-login">
    <span class="title">验证码登录</span>
    <el-form
      ref="ruleFormRef"
      :model="phoneForm"
      label-width="70px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <el-form-item label="手机号:" prop="phone">
        <el-input
          v-model="phoneForm.phone"
          :prefix-icon="Cellphone"
          size="large"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码:" class="codeBox" prop="code">
        <el-input
          v-model="phoneForm.code"
          :prefix-icon="Document"
          size="large"
        ></el-input>
        <el-button type="danger" @click="sendCode" :disabled="isShow">{{
          codeValue
        }}</el-button>
      </el-form-item>
    </el-form>
    <el-button
      type="danger"
      class="login-btn"
      @click="phoneLogin"
      :loading="btnLoading"
      >登录</el-button
    >
  </div>
</template>

<script>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Cellphone, Document } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { loginByPhoneRequest } from "@/service/user-login";
import Cache from "@/utils/Cache";
import { useStore } from "vuex";
export default {
  setup() {
    const ruleFormRef = ref();
    let phoneForm = reactive({
      phone: "13937117595",
      code: "",
    });
    let codeValue = ref("获取验证码");
    let second = ref(60);
    let isShow = ref(false);
    let time = null;
    let btnLoading = ref(false);
    const router = useRouter();
    const store = useStore();
    let rules = reactive({
      phone: [
        { required: true, message: "手机号不能为空", trigger: "change" },
        {
          pattern: /^1[3|5|7|8|9]\d{9}$/,
          message: "请输入正确的号码格式",
          trigger: "blur",
        },
      ],
      code: [
        { required: true, message: "验证码不能为空", trigger: "blur" },
        {
          pattern: /^\d{6}$/,
          message: "验证码长度为6个字符",
          trigger: "blur",
        },
      ],
    });
    // 发送验证码处理
    const sendCode = () => {
      isShow.value = true;
      second.value = 10;
      let number = "";
      //随机生成一个验证码
      for (let i = 1; i <= 6; i++) {
        number += Math.floor(Math.random() * 10);
      }
      phoneForm.code = number;
      //重新发送验证码倒计时
      time = setInterval(() => {
        codeValue.value = `${second.value}s后获取`;
        if (second.value === 0) {
          clearInterval(time);
          isShow.value = false;
          codeValue.value = "获取验证码";
        }
        second.value--;
      }, 1000);
    };
    // 登录按钮逻辑处理
    const phoneLogin = () => {
      ruleFormRef.value.validate((valid) => {
        if (!valid) {
          ElMessage({
            message: "登录失败,手机号或验证码格式错误!",
            type: "error",
            center: true,
          });
          return;
        }
        loginService();
      });
    };
    // 手机登录发送网络请求
    const loginService = async () => {
      btnLoading.value = true;
      try {
        const res = await loginByPhoneRequest(phoneForm);
        Cache.saveItem("token", res.data.token);
        store.commit("setAccount", res.data.account);
        ElMessage({
          message: "登录成功!",
          type: "success",
          center: true,
        });
        router.push("/");
      } catch (err) {
        console.log(err);
        ElMessage({
          message: "登录失败,请使用已存在的手机号登录!",
          type: "error",
          center: true,
        });
      }
      btnLoading.value = false;
    };
    return {
      phoneForm,
      Cellphone,
      Document,
      codeValue,
      sendCode,
      isShow,
      rules,
      phoneLogin,
      ruleFormRef,
      btnLoading,
    };
  },
};
</script>

<style lang="less" scoped>
.phone-login {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  display: flex;
  align-items: center;
  flex-direction: column;
  transform: translateZ(-70px) rotateY(180deg);
  .title {
    display: block;
    text-align: center;
    font-weight: 700;
    font-size: 30px;
    margin-top: 30px;
    margin-bottom: 15px;
    color: #f56c6c;
  }
  .el-form {
    width: 300px;
    height: 100px;
  }
  .codeBox {
    /deep/.el-form-item__content {
      display: flex;
      flex-wrap: nowrap;
      button {
        margin-left: 8px;
      }
    }
  }
  .login-btn {
    width: 250px;
    height: 40px;
    margin-top: 20px;
  }
}
</style>
